package com.box.service.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.camel.component.beanclass.ClassEndpoint;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.box.entity.DbLog;
import com.box.entity.DbOther;
import com.box.entity.DbUsers;
import com.box.entity.DbUsersExample;
import com.box.entity.DbUsersExample.Criteria;
import com.box.entity.UserSearch;
import com.box.mapper.DbLogMapper;
import com.box.mapper.DbUsersMapper;
import com.box.service.OtherService;
import com.box.service.UserService;
import com.box.utils.EmailUtil;
import com.box.utils.LayuiResult;
import com.box.utils.MyUtil;
import com.box.utils.ResponseResult;
import com.box.utils.SessionUtils;
import com.box.utils.SystemInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;



@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private DbUsersMapper usersMapper;
	
	@Value("${MEMBERUSERNAME}")
	private String MEMBERUSERNAME;
	
	@Autowired
	private DbLogMapper logMapper;
	
	@Autowired
	private OtherService otherService;

	public LayuiResult selUsers(Integer page, Integer limit, UserSearch search) {
		// TODO Auto-generated method stub
		try {
			
			//分页
			PageHelper.startPage(page, limit);
			DbUsersExample example=new DbUsersExample();
			example.setOrderByClause("lasttime DESC");
			Criteria createCriteria = example.createCriteria();
			if(search.getNickname()!=null&&!"".equals(search.getNickname())){
				//注意：模糊查询需要进行拼接”%“  如下，不进行拼接是不能完成查询的哦。
				createCriteria.andNicknameLike("%"+search.getNickname()+"%");
			}
			if(search.getSex()!=null&&!"-1".equals(search.getSex())){
				createCriteria.andSexEqualTo(search.getSex());
			}
			if(search.getStatus()!=null&&!"-1".equals(search.getStatus())){
				
				Integer status=Integer.parseInt(search.getStatus());
				createCriteria.andStatusEqualTo(status);
			}
			if(search.getCreateTimeStart()!=null&&!"".equals(search.getCreateTimeStart())){
				createCriteria.andLasttimeGreaterThanOrEqualTo(MyUtil.getDateByString(search.getCreateTimeStart()));
			}
			if(search.getCreateTimeEnd()!=null&&!"".equals(search.getCreateTimeEnd())){
			createCriteria.andLasttimeLessThanOrEqualTo(MyUtil.getDateByString(search.getCreateTimeEnd()));
			}
			List<DbUsers> list = usersMapper.selectByExample(example);
			PageInfo<DbUsers> pageinfo=new PageInfo<DbUsers>(list);
			LayuiResult result=new LayuiResult();
			result.setCode(0);
			result.setMsg("success");
			result.setCount(pageinfo.getTotal());
			result.setData(pageinfo.getList());
			return result;
		} catch (Exception e) {
			// TODO: handle exception
			LayuiResult result=new LayuiResult();
			result.setCode(1);
			result.setMsg("fail");
			result.setCount(null);
			result.setData(e);
			return result;
		}
		
		
		
	
	}

	public DbUsers checkUserByNickname(String nickname, Long uid)
			throws Exception {
		// TODO Auto-generated method stub
		//通过用户名和id进行数据库对比，如果存在就是一致
		DbUsersExample example=new DbUsersExample();
		Criteria create = example.createCriteria();
		//先进行用户名比对，再将id拿出来对比
		create.andNicknameEqualTo(nickname);
		if(uid!=null&&!uid.equals("")){
			create.andUidEqualTo(uid);
		}
		List<DbUsers> userlist = usersMapper.selectByExample(example);
		if(userlist!=null&&userlist.size()>0){
			return userlist.get(0);
		}
		
		
		return null;
	}

	public DbUsers checkUserByEmail(String email, Long uid) throws Exception {
		// TODO Auto-generated method stub
		DbUsersExample example=new DbUsersExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria .andEmailEqualTo(email);
		if(uid!=null&&!uid.equals("")){
			createCriteria.andUidEqualTo(uid);
		}
		List<DbUsers> list = usersMapper.selectByExample(example);
		if(list!=null&&list.size()>0){
			return list.get(0);
		}
		return null;
	}

	
	
	public Integer insertUserBySerliaze(DbUsers users) throws Exception {
		// TODO Auto-generated method stub
		users.setPassword(DigestUtils.md5DigestAsHex(users.getPassword().getBytes()));
		String code=MyUtil.getStrUUID();
		users.seteCode(code);
		users.setStatus(0);//0:未激活，1，正常，2，禁用
		Date date=new Date();		
		users.setLasttime(date);
		//发送邮件工具
		EmailUtil.sendMail(users.getEmail(),code);

		int n = usersMapper.insertSelective(users);
		return n;
	}

	public DbUsers checkUserByUserName(String username, Long uid)
			throws Exception {
		// TODO Auto-generated method stub
		DbUsersExample example=new DbUsersExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andUsernameEqualTo(username);
		List<DbUsers> list = usersMapper.selectByExample(example);
		if(uid!=null&&!uid.equals("")){
			createCriteria.andUidEqualTo(uid);
		
		}
		if(list!=null&&list.size()>0){
			return list.get(0);
		}
		return null;
	}
	public DbUsers checkUsersByPhone(String phone, Long uid) throws Exception {
		// TODO Auto-generated method stub
		DbUsersExample example=new DbUsersExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andTelphoneEqualTo(Long.parseLong(phone));
		List<DbUsers> list = usersMapper.selectByExample(example);
		if(uid!=null&&!uid.equals("")){
			createCriteria.andUidEqualTo(uid);
		}
		if(list!=null&&list.size()>0){
			return list.get(0);
		}
		return null;
	}
	public List<DbUsers> getUserList() {
		// TODO Auto-generated method stub
		DbUsersExample example=new DbUsersExample();
		List<DbUsers> list = usersMapper.selectByExample(example);
		return list;
	}

	public Integer delUserById(String uid) {
		// TODO Auto-generated method stub
		Long id=Long.parseLong(uid);
		int n= usersMapper.deleteByPrimaryKey(id);
		return n;
	}

	public DbUsers selUserById(Long uid) {
		// TODO Auto-generated method stub
		DbUsers users = usersMapper.selectByPrimaryKey(uid);
		
		return users;
	}

	public Integer updUserService(DbUsers users) {
		// TODO Auto-generated method stub
		DbUsers u = usersMapper.selectByPrimaryKey(users.getUid());		
		users.seteCode(u.geteCode());
		users.setPassword(u.getPassword());
		users.setLasttime(u.getLasttime());	
		
	
		
		int n = usersMapper.updateByPrimaryKeySelective(users);
		System.out.println("成功修改用户记录:"+n+"条");
		return n;
	}

	public Integer delUsersService(String userStr) {
		// TODO Auto-generated method stub
		String[] users = userStr.split(",");
		int n =0;
		if(users!=null&&users.length>0){
			for (String uid : users) {
				n= usersMapper.deleteByPrimaryKey(Long.parseLong(uid));
			}
		}
		System.out.println("成功批量删除了"+n+"条记录");
		return n;
	}

	public LayuiResult selUsersByUserNameAndPassword(String userName, String passWord) {
		// TODO Auto-generated method stub
		//判空值
		
		if(StringUtils.isBlank(userName)||StringUtils.isBlank(passWord)){
			
			return new LayuiResult(500,"用户名或密码不能为空");
			
		}

			DbUsersExample example=new DbUsersExample();
			Criteria createCriteria = example.createCriteria();
			createCriteria.andUsernameEqualTo(userName);
		
			List<DbUsers> users = usersMapper.selectByExample(example);
			//账号不存在
			if(users==null||users.size()==0){
				return new LayuiResult(500,"账号不存在");
			}
			//账号或密码不正确
			if(!passWord.equals(users.get(0).getPassword())){
				
				return new LayuiResult(500,"账号或密码不正确");
				
			}
		
			SessionUtils.setSessionAttribute(MEMBERUSERNAME, userName);
			Integer sign = users.get(0).getSign();//88
				Integer c=++sign;
				DbUsers u=new DbUsers();
				u.setUid(users.get(0).getUid());
				u.setSign(c);
				u.setLasttime(new Date());//本次登录时间
				usersMapper.updateByPrimaryKeySelective(u);
		
		

			//写入日志
				SystemInfo instance = SystemInfo.getInstance();
				DbLog log=new DbLog();
				log.setUsername(userName);
				log.setCreateTime(users.get(0).getLasttime());//上次登录时间
				log.setIp(instance.getIP());
				
				String method= this.getClass().getName();  
				log.setParams(users.get(0).getNickname());
				log.setMethod(method);
				log.setParams(instance.getSystemName());
			
				log.setOperation(instance.getMac());
				
				logMapper.insert(log);
		
		
			
				
			
		
	return new LayuiResult(0, "登录成功");


	}

	public String getSessionMemberByUserName(){
		String username = SessionUtils.getSessionAttribute(MEMBERUSERNAME).toString();
		if(username!=null){
			return username;
		}else{
			return "404";
		}

	}
	
	public LayuiResult insertUsersBySelectTive(String userName, String passWord, String phone, String email) throws Exception{
		// TODO Auto-generated method stub
		Integer n=0;
		if(StringUtils.isBlank(userName)||StringUtils.isBlank(passWord)||StringUtils.isBlank(phone)||StringUtils.isBlank(email)){
			
			return new LayuiResult(500,"用户名或密码或手机号或邮箱不能为空");
		}
		
		DbUsers user=new DbUsers();	
		user.setUsername(userName);
		passWord=DigestUtils.md5DigestAsHex(passWord.getBytes());
		user.setPassword(passWord);
		String code=MyUtil.getStrUUID();
		SystemInfo system = SystemInfo.getInstance();
		user.setIp(system.getIP());
		user.seteCode(code);
		user.setTelphone(Long.parseLong(phone));
		user.setEmail(email);
		user.setSign(1);
		user.setMname("无");
		user.setPayaccount((short)0);
		user.setNickname("君无邪");
		user.setAlt("无");
		user.setLasttime(new Date());//第一次登录时间为注册时候
		n=usersMapper.insertSelective(user);
		//发送邮件工具
		try {
			EmailUtil.sendMail(user.getEmail(),code);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("邮箱秘钥出问题了...");
		}
	

		//注册成功后写入注册表
		try {
			DbUsersExample example = new DbUsersExample();
			Criteria createCriteria = example.createCriteria();
			createCriteria.andUsernameEqualTo(userName);
			List<DbUsers>  list= usersMapper.selectByExample(example);
			DbOther o=new DbOther();
			o.setUid(list.get(0).getUid().intValue());
			o.setRegisterTime(new Date());
			otherService.insertOther(o);
			n=2;
			System.out.println(n+"写入注册表中成功");
		} catch (Exception e) {
			// TODO: handle exception
			n=0;
			System.out.println(n+"写入失败:用户id-"+user.getUid());
		}
	
		System.out.println(n+"注册成功");
		return new LayuiResult(0,"注册成功"+n);
	}

	public DbUsers selUsersByUserName() {
		// TODO Auto-generated method stub
	String username = getSessionMemberByUserName();
	System.out.println("用户service中是否获取到用户名:"+username);
	DbUsersExample example=new DbUsersExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andUsernameEqualTo(username);
		List<DbUsers> list = usersMapper.selectByExample(example);
		SystemInfo system = SystemInfo.getInstance();
		DbUsers u=new DbUsers();

	
		
		u.setIp( system.getIP());
		u.setUid(list.get(0).getUid());

Integer n=		usersMapper.updateByPrimaryKeySelective(u);
System.out.println(n+"登录时候成功修改记录");
		return  list.get(0);
	}

	public Integer updateByUsers(DbUsers users) {
		// TODO Auto-generated method stub
		
		return usersMapper.updateByPrimaryKeySelective(users);
	}

	public ResponseResult updateUser(String userName, String nicknamem, String passWord, Long telphone) throws Exception {
		// TODO Auto-generated method stub
		Integer n=0;
		try {
			String usersname = SessionUtils.getSessionAttribute(MEMBERUSERNAME).toString();
			DbUsersExample example  = new DbUsersExample();
			Criteria createCriteria = example.createCriteria();
			createCriteria.andUsernameEqualTo(usersname);
			List<DbUsers> list = usersMapper.selectByExample(example);
			Long uid = list.get(0).getUid();
			DbUsers u=new DbUsers();
			if(StringUtils.isBlank(userName)||StringUtils.isBlank(passWord)||telphone==null||StringUtils.isBlank(nicknamem)){
				n=0;
				return ResponseResult.build(n, "用户名或密码或其余信息有误,请查看");
			}
			u.setPassword(passWord);
			u.setUsername(userName);	
			u.setTelphone(telphone);
			u.setNickname(nicknamem);
			u.setUid(uid);
			
			n=usersMapper.updateByPrimaryKeySelective(u);
			System.out.println(n+"..............成功修改用户信息");
			return ResponseResult.build(n, "修改成功");
		} catch (Exception e) {
			// TODO: handle exception
			n=0;
			return ResponseResult.build(n, "修改失败", e);
			
		}
	

	}

	@Override
	public void addCookie(HttpServletRequest request, HttpServletResponse response, String userName, String passWord) throws Exception {
		// TODO Auto-generated method stub
		if(!userName.equals("") && !passWord.equals("")){
			//创建cookie
			Cookie cookieAccount=new Cookie("account",userName);
			Cookie cookiePassWord=new Cookie("account",userName);
			//设置Cookie的父路径
			cookieAccount.setPath(request.getContextPath()+"/");
			cookiePassWord.setPath(request.getContextPath()+"/");
			//获取是否保存cookie?
			String rememberMe = request.getParameter("rememberMe");
	        if( rememberMe==null || rememberMe.equals(false) ){
	            //不保存Cookie
	        	cookieAccount.setMaxAge(0);
	        	cookiePassWord.setMaxAge(0);
	        }else{
	            //保存Cookie的时间长度，单位为秒
	        	cookieAccount.setMaxAge(7*24*60*60);
	        	cookiePassWord.setMaxAge(7*24*60*60);
	        }
	        //加入Cookie到响应头
	        response.addCookie(cookieAccount);
	        response.addCookie(cookiePassWord);
		}

	}

	

}
